<template>
  <div>
    <!-- 订货单审核-->
    <TopFilter :list="topFilterList" ref="top" :cols="3" @filterChange="changeHandle" @onCollapse="collapseHandle" :labelWidth="110" @resetChange="resetChange" :isSubmitBtn="isShowBtn"></TopFilter>
    <Spin :spinning="exportLoading" tip="Loading...">
      <el-tabs v-model="activeName" @tab-click="tabsHandleClick" :before-leave="beforeHandle">
        <el-tab-pane label="采购订单" name="first">
          <FilterTable
            ref="table"
            :columns="columns"
            :fetchapi="fetchApi"
            :params="fetchParams"
            :datakey="'records'"
            columnsRef="wkcOrderQueryC"
            :isSelectColumn="true"
            :onRowSelectChange="selectChangeHandle"
            :onColumnsChange="(columns) => (this.columns = columns)"
          >
            <template slot="controls">
              <multiuse-button size="small" type="primary" @click="addHandle(1)">导 出</multiuse-button>
            </template>
          </FilterTable>
        </el-tab-pane>
        <el-tab-pane label="订单车辆" name="second">
          <FilterTable
            ref="tableInfo"
            height="auto"
            :columns="columns1"
            :isSelectColumn="true"
            :datakey="'records'"
            columnsRef="wkcOrderQueryC1"
            :fetchapi="fetchApi1"
            :params="fetchParams1"
            :dataSource="tableList1"
            :onRowSelectChange="selectChangeHandle1"
            :onColumnsChange="(columns1) => (this.columns1 = columns1)"
          >
            <template slot="controls">
              <multiuse-button size="small" type="primary" @click="addHandle(2)">保 存</multiuse-button>
            </template>
          </FilterTable>
        </el-tab-pane>
      </el-tabs>
    </Spin>

    <Drawer :visible.sync="detailVisible" :title="'订单信息'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="72%">
      <detailModel :rowData="formData" @close="emitcloseHandler" />
    </Drawer>
  </div>
</template>
<script>
import { getList, getdeliveryList, exporturl, saveList, delByDeliveryId, exportDlrCheck } from '@/api/dealerSale/OrderManagement/OrderQueryC';
import detailModel from './detailModel';
import { exportFile, exportExcelFile } from '@/utils';
import { dictionary } from '@/utils/dictMixin';
import moment from 'moment';
export default {
  name: 'acknowledgementOrder',
  data() {
    this.BaseTable = null;
    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      columns1: this.createdTable1(),
      fetchParams: {
        isDealer: 10041001,
        isUnshowUnreport: 10041001,
      },
      fetchApi: getList,
      fetchParams1: {},
      fetchApi1: getdeliveryList,
      formData: {},
      exportLoading: false,
      issearch: false,
      detailVisible: false,
      isAccountProject: false,
      tableList1: [],
      ProjectId: '',
      activeName: 'first',
      selectList: [],
      selectList1: [],
      isShowBtn: true,
    };
  },
  components: {
    detailModel,
  },
  mixins: [dictionary],
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.table = this.$refs.tableInfo.$refs.pageTable;
  },
  created() {},
  methods: {
    beforeHandle() {
      for (let i in this.selectList) {
        if (this.selectList[i].orderStatus === 24081001) {
          this.activeName = 'first';
          this.$notify({
            title: '警告',
            message: '将未提报订单提报后查看',
            type: 'warning',
          });
          return false;
        }
      }
      if (this.selectList.length === 0) {
        this.activeName = 'first';
        this.$notify({
          title: '警告',
          message: '至少选择一条数据',
          type: 'warning',
        });
        return false;
      }
    },
    async tabsHandleClick(tab, event) {
      if (tab.index === '1') {
        this.isShowBtn = false;
        let ids = [];
        this.selectList.forEach((e) => {
          ids.push(e.orderId);
        });
        this.fetchParams1.ids = ids;
        this.fetchParams1 = Object.assign({}, this.fetchParams1);
      }
      if (tab.index === '0') {
        this.tableList1 = [];
        this.isShowBtn = true;
      }
    },
    createdFrom() {
      return [
        {
          type: 'INPUT',
          label: '订单编号',
          fieldName: 'orderNo',
          placeholder: '请输入',
        },
        {
          type: 'DATE',
          label: '订单年月',
          fieldName: 'orderYearMonth',
          placeholder: '请输入',
          dateType: 'month',
          // initialValue: moment().format('YYYY-MM')
        },
        {
          type: 'RANGE_DATE',
          label: '创建日期',
          fieldName: 'startDate|endDate',
          placeholder: '请选择',
          initialValue: [],
          dateType: 'exactdaterange',
        },
        {
          type: 'SELECT',
          label: '订单状态',
          fieldName: 'orderStatus',
          placeholder: '请选择',
          itemList: this.createDictList('2408'),
        },
        {
          type: 'SELECT',
          label: '订单类型',
          fieldName: 'orderType',
          placeholder: '请选择',
          itemList: this.createDictList('2410'),
        },
        {
          type: 'SELECT',
          label: '紧急度',
          fieldName: 'emergencyType',
          placeholder: '请选择',
          itemList: this.createDictList('2101'),
        },
      ];
    },

    selectChangeHandle(row) {
      this.selectList = row;
    },
    selectChangeHandle1(row) {
      this.selectList1 = row;
    },
    async addHandle(type) {
      if (type == 1) {
        this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
          confirmButtonText: '下载',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.$refs.top.SUBMIT_FORM();
            this.exportLoading = true;

            exportDlrCheck(this.fetchParams)
              .then((response) => {
                exportExcelFile(response.data, 'C端订单查看');
                // exportFile(response.data, '订单明细查询', 'csv');
                this.exportLoading = false;
              })
              .catch((err) => {
                console.log(err);
              });
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消',
            });
          });
      } else if (type == 2) {
        let arr = [];
        for (let i in this.selectList1) {
          if (this.selectList1[i].orderDetailType !== 24151001) {
            arr.push(this.selectList1[i].doNo);
          }
        }
        console.log(arr);
        if (arr.length > 0) {
          this.$notify({
            title: '警告',
            message: '只能保存待审核数据',
            type: 'warning',
          });
          return;
        }
        await this.$confirm('是否保存选定的数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            //todo 保存
            let res = await saveList(this.selectList1);
            if (res.resultCode == 200) {
              this.$notify({
                title: '成功',
                message: '保存成功',
                type: 'success',
              });
              this.isOpen = true;
              this.activeName = 'first';
              this.table.EXECUTE_DELETE(this.selectList1);
              this.fetchParams = Object.assign({}, this.fetchParams);
            }
          })
          .catch(() => {});
      }
    },
    changeHandle(params) {
      this.fetchParams.projectCode = this.ProjectId;
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    async editHandle(data, type) {
      if (type === 2) {
        this.formData = data;
        this.detailVisible = true;
      } else if (type === 1) {
        await this.$confirm('是否确定取消?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            let res = await delByDeliveryId({ id: data.id });
            if (res.resultCode == 200) {
              let ids = [];
              this.selectList.forEach((e) => {
                ids.push(e.orderId);
              });
              this.fetchParams1.ids = ids;
              this.fetchParams1 = Object.assign({}, this.fetchParams1);
              this.$notify({
                title: '成功',
                message: '取消成功',
                type: 'success',
              });
            }
          })
          .catch(() => {});
      }
    },
    emitcloseHandler() {
      this.detailVisible = false;
    },
    resetChange(val) {
      // this.ProjectId = '';
      // this.fetchParams.projectCode = '';
      this.fetchParams = Object.assign({}, this.fetchParams);
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        // {
        //   title: '操作',
        //   dataIndex: 'column-action',
        //   width: 50,
        //   fixed: 'left',
        //   render: (props, h) => {
        //     return (
        //       <div>
        //       <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row, 2)}>
        //     详情
        //     </multiuse-button>
        //     </div>
        //   );
        //   }
        // },
        {
          title: '订单编号',
          dataIndex: 'orderNo',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '订单类型',
          dataIndex: 'orderType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2410'),
          render: (p) => {
            return <span>{this.createDictText(p.row.orderType, '2410')}</span>;
          },
        },
        {
          title: '紧急度',
          dataIndex: 'emergencyType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2101'),
          render: (p) => {
            return <span>{this.createDictText(p.row.emergencyType, '2101')}</span>;
          },
        },
        {
          title: '订单状态',
          dataIndex: 'orderStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2408'),
          render: (p) => {
            return <span>{this.createDictText(p.row.orderStatus, '2408')}</span>;
          },
        },
        {
          title: '订单年月',
          dataIndex: 'orderYearMonth',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '运输方式',
          dataIndex: 'transportType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2409'),
          render: (p) => {
            return <span>{this.createDictText(p.row.transportType, '2409')}</span>;
          },
        },
        {
          title: '提报数量',
          dataIndex: 'orderTotalNum',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '创建人',
          dataIndex: 'createdBy',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
      ];
    },
    createdTable1() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row, 2)}>
                  详情
                </multiuse-button>
                <el-divider direction="vertical" />
                <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row, 1)}>
                  取消
                </multiuse-button>
              </div>
            );
          },
        },
        {
          title: '是否最优先结算',
          dataIndex: 'firstPrioritySettle',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          defaultEditable: true,
          editType: 'checkbox',
          editItems: [
            { text: '', trueValue: 10041001 },
            { text: '', falseValue: 10041002 },
          ],
          onChange: (index, data) => {
            if (data.firstPrioritySettle === 10041001) {
              data.prioritySettle = 10041002;
            }
          },
        },
        {
          title: '是否优先结算',
          dataIndex: 'prioritySettle',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          defaultEditable: true,
          editType: 'checkbox',
          editItems: [
            { text: '', trueValue: 10041001 },
            { text: '', falseValue: 10041002 },
          ],
          onChange: (index, data) => {
            if (data.prioritySettle === 10041001) {
              data.firstPrioritySettle = 10041002;
            }
          },
        },
        {
          title: '订单编号',
          dataIndex: 'orderNo',
          sorter: true,
          filter: true,
          filterType: 'input',
          align: 'center',
          width: 200,
        },
        {
          title: '订单管理号',
          dataIndex: 'doNo',
          sorter: true,
          filter: true,
          filterType: 'input',
          align: 'center',
          width: 200,
        },
        {
          title: '订单类型',
          dataIndex: 'orderType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2410'),
          render: (p) => {
            return <span>{this.createDictText(p.row.orderType, '2410')}</span>;
          },
        },
        {
          title: '紧急度',
          dataIndex: 'emergencyType',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (p) => {
            return <span>{this.createDictText(p.row.emergencyType, '2101')}</span>;
          },
        },
        // {
        //   title: '订单来源',
        //   dataIndex: 'isApp',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   // render: p => {
        //   //   return <span>{this.createDictText(p.row.orderDetailType, '2415')}</span>;
        //   // }
        // },
        {
          title: '订单明细状态',
          dataIndex: 'orderDetailType',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (p) => {
            return <span>{this.createDictText(p.row.orderDetailType, '2415')}</span>;
          },
        },
        {
          title: '订单年月',
          dataIndex: 'orderYearMonth',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '车辆用途',
          dataIndex: 'vehicleUse',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (p) => {
            return <span>{this.createDictText(p.row.vehicleUse, '2406')}</span>;
          },
        },

        {
          title: '资金类型',
          dataIndex: 'accountId',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'select',
          editRequired: true,
          rules: [{ required: true, message: '请填写正整数', trigger: 'blur' }],
          render: (p) => {
            return (
              <el-select
                size="mini"
                v-model={p.row.accountId}
                required
                disabled={p.row.orderDetailType !== 24151001}
                placeholder="请选择"
                onChange={(value) => {
                  p.row.accountId = value;
                  for (let x of p.row.accountTypes) {
                    if (x.accountId == value) {
                      p.row.ownFund = x.ownFund;
                      p.row.tripFund = x.tripFund;
                      break;
                    }
                  }
                }}
              >
                {p.row.accountTypes.map((item) => (
                  <el-option key={item.accountId} label={item.accountTypeName} value={item.accountId} />
                ))}{' '}
              </el-select>
            );
          },
        },

        {
          title: '市场指导价',
          dataIndex: 'singleAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
        },

        {
          title: '基础折扣',
          dataIndex: 'discountAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
        },
        {
          title: '终端奖',
          dataIndex: 'sapTerminalBonus',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
        },
        {
          title: '优质服务奖',
          dataIndex: 'sapServiceBonus',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
        },
        {
          title: '促销1',
          dataIndex: 'sapPromotionPriceA',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
        },
        {
          title: '促销2',
          dataIndex: 'sapPromotionPriceB',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
        },
        // {
        //   title: '促销4',
        //   dataIndex: 'discountAmount4',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   precision: 2,
        // },
        {
          title: '结算价格',
          dataIndex: 'sapSettlementPrice',
          sorter: true,
          filter: true,
          filterType: 'input',
          width: 100,
          precision: 2,
        },
        {
          title: '是否使用返利',
          dataIndex: 'isRebate',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: (p) => {
            return <span>{this.createDictText(p.row.isRebate, '1004')}</span>;
          },
        },
        {
          title: '返利使用金额',
          dataIndex: 'singleRebateAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
        },

        {
          title: '运输方式',
          dataIndex: 'transportType',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (p) => {
            return <span>{this.createDictText(p.row.transportType, '2409')}</span>;
          },
        },
        {
          title: '收车地址',
          dataIndex: 'addressId',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (p) => {
            return (
              <el-select
                size="mini"
                v-model={p.row.addressId}
                required
                disabled={p.row.orderDetailType !== 24151001}
                placeholder="请选择"
                onChange={(value) => {
                  p.row.addressId = value;
                  p.row.addressDTOS.map((x) => {
                    if (x.addressId == value) {
                      p.row.linkMan = x.linkMan;
                      p.row.cityName = x.cityName;
                      p.row.linkPhone = x.linkPhone;
                    }
                  });
                }}
              >
                {p.row.addressDTOS.map((item) => (
                  <el-option key={item.addressId} label={item.address} value={item.addressId} />
                ))}{' '}
              </el-select>
            );
          },
        },
        {
          title: '送达城市',
          dataIndex: 'cityName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '联系人',
          dataIndex: 'linkMan',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '联系电话',
          dataIndex: 'linkPhone',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '物料编码',
          dataIndex: 'productCode',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '物料描述',
          dataIndex: 'productName',
          align: 'center',
          width: 400,
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '车系名称',
          dataIndex: 'seriesName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '车型名称',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '配置',
          dataIndex: 'configName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '选装',
          dataIndex: 'optionName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '内饰',
          dataIndex: 'trimName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '外饰',
          dataIndex: 'colorName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
      ];
    },
  },
};
</script>
<style lang="less" scoped>
.el-tabs {
  /deep/ .el-tabs__header {
    margin: 0;
  }
  /deep/ .el-tabs__nav-wrap {
    background-color: #ffffff;
    padding-left: 24px;
    .el-tabs__item {
      // height: 32px;
      // line-height: 32px;
      height: 42px;
      line-height: 42px;
      font-size: 16px;
    }
    &.is-top::after {
      height: 1px;
    }
    &.is-left::after {
      width: 1px;
    }
  }
  /deep/ .el-tabs__content {
    position: static !important;
    background: #fff;
  }
}
</style>